package com.dingwen.treasure.manage.controller;

import com.dingwen.treasure.base.constant.RedisConstant;
import com.dingwen.treasure.base.controller.BaseViewController;
import com.dingwen.treasure.base.pojo.vo.Result;
import com.dingwen.treasure.common.redis.service.RedisService;
import com.dingwen.treasure.core.service.CaptchaService;
import com.dingwen.treasure.manage.service.LoginService;
import com.dingwen.treasure.model.dto.LoginDto;
import com.dingwen.treasure.model.vo.LoginVo;
import com.dingwen.treasure.security.dto.LoginUser;
import com.dingwen.treasure.security.service.TokenService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;


/**
 * 　登录
 * 　@author dingwen
 * 　@date 2022/6/23
 */
@Api(tags = "登录")
@RestController
@Slf4j
@RequestMapping("sys/login")
public class SysLoginController implements BaseViewController {

    /**
     * 验证码校验服务
     */
    @Resource
    private CaptchaService captchaService;

    /**
     * redis 服务
     */
    @Resource
    private RedisService redisService;

    /**
     * login service
     */
    @Resource
    private LoginService loginService;


    /**
     * tokenService
     */
    @Resource
    private TokenService tokenService;

    /**
     * 登录 </br>
     * 缓存也可以考虑 {@code easy cache}实现缓存逻辑
     *
     * @param loginDTO 登录数据传输对象
     * @return {@link Result}<{@link LoginVo}>
     */
    @PostMapping()
    public Result<LoginVo> login(@RequestBody @Validated LoginDto loginDTO) {
        // 1. 验证码校验
        String key = RedisConstant.CAPTCHA_KEY.concat(loginDTO.getCodeKey());
        captchaService.validate(String.valueOf(loginDTO.getCode()), redisService.getCacheObject(key));

        // 2. 登录逻辑 (缓存用户信息、token信息) 实时调库，并进行缓存
        LoginUser loginUser = loginService.doLogin(loginDTO.getAccount(), loginDTO.getPassword());

        // 缓存vo token
        String token = tokenService.generateWebToken(loginUser);

        // 已做缓存处理 优先返回缓存
        LoginVo loginVo = loginService.buildLoginVo(loginUser.getUser(), token);


        // 3. 删除验证码 key
        redisService.deleteObject(key);

        return success(loginVo);
    }
}
